# 生命周期
#coding=utf-8
from doctest import debug
from math import erf, inf
from uu import Error
from fastapi import FastAPI
from contextlib import asynccontextmanager
from src.utils.config import read_config
# from tortoise.contrib.fastapi import register_tortoise
# from aioredis import create_redis_pool, Redis
import aioredis
from influxdb import InfluxDBClient
from src.core.mysql_core import init_mysql 
# 导入定时任务
from src.scheduler import scheduler
 

# 生命周期函数，监听服务启动完毕和服务结束

REDIS = {}
MYSQL = {} 
INFLUXDB={} 

@asynccontextmanager
async def lifespan(app: FastAPI):
    # Load the ML model
    # 将配置文件的配置挂在在app上
    config = read_config()
    app.state.config = config

    # redis 配置
    # try:
    redisConfig = config["redis"]
    mysqlConfig = config["mysql"]
    
    print(redisConfig)
    
   
    try:
      
        # 连接redis
        for redisk in redisConfig:
            redis = redisConfig.get(redisk)
            REDIS[redisk] = await aioredis.from_url(
                f'redis://{redis["ip"]}', 
                username=redis["username"], 
                password=redis["password"],
                port=redis["port"],
                db=redis["db"]
            )
             
            print(f"\033[1;32m========= redis-{redisk} connect success !!!=======\033[1;32m")
        app.redis = REDIS 
        
        # 连接mysql(OK)
        for mysql in mysqlConfig:
            sql = mysqlConfig.get(mysql)
            MYSQL[mysql] = await init_mysql(host=sql["host"],
                                 port=sql["port"],
                                 user=sql["username"],
                                 password=sql["password"],
                                 db=sql["database"], debug=True)  
            print(f"\033[1;32m========= mysql-{mysql} connect success !!!=======\033[1;32m")

        app.mysql = MYSQL   
        # res = await MYSQL["base"].queryList("select * from users where user_id in ( :userId ) and account=:account", {
        #     "replacement": {
        #         "userId": [1],
        #         "account": "admin"
        #     } 
        # })    
        # print(res)

        # Influxdb 案例
        # infux = config.get("influxdb")
        # try:
        #  INFLUXDB
        #     infux_client = InfluxDBClient(infux["host"], infux["port"], infux["username"], infux["password"])  # 连接数据库
        #     result = infux_client.query('select * from test;', database='test')
        #     print("result", result)
        # except Error:
        #     print("influx", Error)

    except IOError:
        print("连接Redis失败：", IOError)
 

    print("\033[1;32m========= app ready success !!!=======\033[1;32m")

    # 启动定时任务
    scheduler.start()
    print("任务队开始")

    yield # 在 `yield` 之前，将在应用程序启动之前执行；而 `yield` 之后的部分将在应用程序完成之后执行。

    # 关闭定时任务
    scheduler.shutdown()
    print("任务队结束")

    print("生命到头")
 